package com.cmes.system.core.service;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cmes.jdbc.service.GenericService;
import com.cmes.system.core.entity.UserDeptEntity;
import com.cmes.system.core.repository.UserDeptRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户部门关系管理
 *
 * @author Bruce.Gong
 * @since 1.0.0-SNAPSHOT
 */
@Slf4j
@RequiredArgsConstructor
@Service
@Transactional(propagation = Propagation.SUPPORTS, rollbackFor = Exception.class)
public class UserDeptService extends GenericService<UserDeptRepository, UserDeptEntity> {

    public boolean add(Long userId, Long deptId) {
        return insert(UserDeptEntity.builder()
                .userId(userId)
                .deptId(deptId)
                .build());
    }

    public boolean add(Long userId, List<Long> deptIds) {
        return insertBatch(deptIds.stream()
                .map(v -> UserDeptEntity.builder()
                        .userId(userId)
                        .deptId(v)
                        .build())
                .collect(Collectors.toList()));
    }

    public boolean deleteByDeptId(Long deptId) {
        return delete(Wrappers.<UserDeptEntity>lambdaUpdate().eq(UserDeptEntity::getDeptId, deptId));
    }

    public boolean deleteByDeptIds(Collection<Long> deptIds) {
        return delete(Wrappers.<UserDeptEntity>lambdaUpdate().in(UserDeptEntity::getDeptId, deptIds));
    }

    public boolean deleteByUserId(Long userId) {
        return delete(Wrappers.<UserDeptEntity>lambdaUpdate().eq(UserDeptEntity::getUserId, userId));
    }

    public boolean deleteByUserIds(Collection<Long> userIds) {
        return delete(Wrappers.<UserDeptEntity>lambdaUpdate().in(UserDeptEntity::getUserId, userIds));
    }

}
